package com.customization.api.pdf2word.cmd;

import com.customization.commons.Console;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.ParamUtil;
import com.engine.core.interceptor.CommandContext;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import weaver.conn.RecordSet;
import weaver.file.AESCoder;
import weaver.file.ImageFileManager;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.workflow.workflow.WorkflowComInfo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

public class CollectWordsCmd  extends AbstractCommonCommand<Map<String,Object>> {
    private HttpServletRequest request=null;
    private HttpServletResponse response=null;
    public CollectWordsCmd(HttpServletRequest request, HttpServletResponse response){
        this.request=request;
        this.response=response;
        Console.log("ReadDocsPictureByOrgCmd=request:" + request + ";response:" + response);
        this.user= HrmUserVarify.getUser(request, response);
        this.params= ParamUtil.request2Map(request);

    }
    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Console.log("params:"+params);
        Console.log("user:"+user.getLastname()+";"+user.getUID());

        JSONObject result= new JSONObject();//返回结果

        JSONObject apidesc= new JSONObject();//接口描述
        JSONObject resultDesc= new JSONObject();//返回值说明
        JSONObject paramsDesc= new JSONObject();//参数传入说明

        Map<String, Object> apidatas = new HashMap<String, Object>();
        result.put("status","-1");
        resultDesc.put("status","-1:传入参数不完整; -2:不存在入参docID对应的附件;-3:未设置字段匹配的正则表达式; 0:正常返回提取到的数据");
        resultDesc.put("result","返回的识别结果");

        String docid= Util.null2String(params.get("docid"));
        paramsDesc.put("docid","传递当前流程的需要提取的附件ID");

        String wfid= Util.null2String(params.get("wfid"));
        paramsDesc.put("wfid","传递当前流程的流程id");

        if(!docid.isEmpty()&&!wfid.isEmpty()){
            
            // 获取http传过来的参数
            
            RecordSet rs= new RecordSet();
            String sql=" select docimagefile.imagefileid as imagefileid,filerealpath,imagefiletype,imagefile.imagefilename,iszip,IMAGEFILETYPE,AESCODE,ISAESENCRYPT  from imagefile,docimagefile "
                    + " where imagefile.imagefileid =docimagefile.imagefileid  and  docimagefile.docid='"+docid+"'";
            rs.execute(sql);
            Console.log("附件SQL:"+sql);
            if(rs.getCounts()>0){
                rs.first();
                // 设置http的头部，可设置下载的zip的文件名
                String filerealpath=rs.getString("filerealpath");
                String  imagefileid=rs.getString("imagefileid");

                String ISAESENCRYPT=rs.getString("ISAESENCRYPT");
                String AESCODE=rs.getString("AESCODE");

                int iszip=rs.getInt("iszip");

                Console.log("iszip==>"+iszip+",filerealpath=====>"+filerealpath);
                ZipFile zf = null;
                ZipInputStream zin = null;
                ZipEntry ze = null;
                InputStream is = null;
                File file =null;

                try {
                    if(1==iszip) {
                        Console.log("压缩文件");
                        zf = new ZipFile(filerealpath);
                        zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(filerealpath)));
                        ze = zin.getNextEntry();
                        is = zf.getInputStream(ze);
                    }else{
                        ImageFileManager imageFileManager=new ImageFileManager();
                        imageFileManager.getImageFileInfoById(Util.getIntValue(imagefileid,0));
                        is=imageFileManager.getInputStream();
                        Console.log("非压缩文件");
                    }
                    if (ISAESENCRYPT.equals("1")) {
                        try {
                            is = AESCoder.decrypt(is, AESCODE);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    // URLEncoder.encode(filename,"utf-8");

                    Console.log("文件流读取完成");
                    PDDocument   document = PDDocument.load(is);
                    //获取内容信息
                    PDFTextStripper pts = new PDFTextStripper();
                    String content = pts.getText(document);
                    Console.log("解析到的文件内容:"+content);


                    WorkflowComInfo workflowComInfo=new WorkflowComInfo();
                    Console.log("当前流程wfid:"+wfid);
                    String Activeversionid= Util.null2String(workflowComInfo.getActiveversionid(wfid));
                    Console.log("当前流程活动版本wfid:"+Activeversionid);
                    if(!Activeversionid.isEmpty()){
                        wfid=Activeversionid;
                    }
                    Console.log("最终流程wfid:"+wfid);


                    String mainid="0";
                    sql=" select * from uf_pdf2txt where wfid  in (select id from  workflow_base where  activeversionid ='"+wfid+"' or  id  ='"+wfid+"')  and sfqy =0 ";
                    Console.log("查询mainid:"+sql);
                    rs.execute(sql);
                    int c=rs.getCounts();
                    if(c>0){
                    if(rs.next()) mainid= rs.getString("id");


                    RecordSet rs2= new RecordSet();
                    sql=" select * from uf_pdf2txt_dt1 where MAINID='"+mainid+"' ";
                    rs2.execute(sql);
                    Console.log("查询提取规则执行SQL:"+sql);
                    Console.log("查询提取规则执行数量:"+rs2.getCounts());


                        JSONArray  jsonArray=new JSONArray();
                        while (rs2.next()){
                            JSONObject  json =new JSONObject();
                            String zdsjkzdmc=rs2.getString("zdsjkzdmc");//数据库字段名称
                            String pattern = rs2.getString("tqzzbds");//正则表达式
                            String zdxsm=rs2.getString("zdxsm");//字段ID
                            String zdname=rs2.getString("zdname");//字段ID
                            String jdth=rs2.getString("jdth");//简单替换规则

                            if(pattern.equals("")){
                                continue;
                            }

                            json.put("fieldname",zdsjkzdmc);
                            json.put("fieldid",zdxsm);
                            json.put("fielddesc",zdname);

                            json.put("value","");
                            json.put("desc","");


                            Pattern r = Pattern.compile(pattern);
                            // 现在创建 matcher 对象
                            Matcher m = r.matcher(content);
                            if (m.find( )) {
                                Console.log(zdname+": " + m.group() );
                                String res=getStringNoBlank(m.group());


                                //替换格式 SDSD==A&&AS==1233
                                if(jdth.contains("==")) {
                                    json.put("oldvalue",res);
                                    String[] reg = jdth.split("&&");
                                    for (int i = 0; i < reg.length; i++) {
                                        String[] cv = reg[i].split("==");
                                        for (int j = 0; j < cv.length; j++) {
                                            if (cv.length == 2) {
                                                res = res.replace(cv[0], cv[1]);
                                            }
                                        }
                                    }
                                }


                                json.put("value",res);
                            } else {
                                Console.log(zdname+"："+"NO MATCH");
                                json.put("desc","未匹配的到");
                            }
                            jsonArray.add(json);
                            result.put("status","0");
                        }
                        result.put("data",jsonArray);

                    }else{
                        result.put("status","-3");
                    }



                } catch (Exception e) {
                    e.printStackTrace();
                } finally {


                }
                

            }else{
                result.put("status","-2");
            }

        }



        apidesc.put("params",paramsDesc);
        apidesc.put("result",resultDesc);
        apidatas.put("apiDataDesc",apidesc);
        apidatas.put("apidata",result);

        return apidatas;
    }



    public static String getStringNoBlank(String str) {


        if(str!=null && !"".equals(str)) {


            Pattern p = Pattern.compile("\\s*|\t|\r|\n");


            Matcher m = p.matcher(str);


            String strNoBlank = m.replaceAll("");


            return strNoBlank;


        }else {


            return str;


        }


    }
}
